#include"SList.h"

// 动态申请一个节点
SListNode* BuySListNode(DataType x) {
	SListNode* node = (SListNode*)malloc(sizeof(SListNode));
	if (node == NULL) {
		return NULL;
	}
	node->data = x;
	node->next = NULL;
	return node;	   
}
// 单链表打印
void SListPrint(SListNode* plist) {
	SListNode* cur = plist;
	while (cur) {
		printf("%d---->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}
// 单链表尾插
void SListPushBack(SListNode** pplist, DataType x) {
	assert(pplist);
	SListNode* cur = *pplist;
	//链表为空
	if (*pplist == NULL) {
		SListNode* newnode = BuySListNode(x);
		newnode->next = *pplist;
		*pplist = newnode;
	}
	else
	{
		SListNode* cur2 = NULL;
		SListNode* newnode = BuySListNode(x);
		while (cur) {
			cur2 = cur;
			cur = cur->next;
		}
		cur2->next = newnode;
	}
}
// 单链表的头插
void SListPushFront(SListNode** pplist, DataType x) {
	assert(pplist);
	//链表为空
	SListNode* newnode = BuySListNode(x);
	newnode->next = *pplist;
	*pplist = newnode;
}
// 单链表的尾删
void SListPopBack(SListNode** pplist) {
	assert(pplist);
	SListNode* cur = *pplist;
	//链表为空
	while (cur) {
		if (cur->next->next == NULL) {
			break;
		}
		cur = cur->next;
	}
	cur->next = NULL;
	free(cur->next);
}
// 单链表头删
void SListPopFront(SListNode** pplist) {
	assert(pplist);
	SListNode* cur = *pplist;
	cur = cur->next;
	*pplist = cur;
}
// 单链表查找
SListNode* SListFind(SListNode* plist, DataType x) {
	assert(plist);
	SListNode* cur = plist;
	while (cur) {
		if (cur->data == x) {
			return cur;
		}
		cur = cur->next;
	}
	printf("未找到%d\n", x);
	return NULL;
}
// 单链表在pos位置之后插入x
// 分析思考为什么不在pos位置之前插入？
void SListInsertAfter(SListNode* pos, DataType x) {
	if (pos == NULL) {
		return;
	}
	SListNode* cur1 = BuySListNode(x);
	cur1->next = pos->next;
	pos->next = cur1;
}
// 单链表删除pos位置之后的值
// 分析思考为什么不删除pos位置？
void SListEraseAfter(SListNode* pos) {
	if (pos == NULL) {
		return;
	}
	SListNode* cur1 = NULL;
	cur1 = pos->next->next;
	pos->next = cur1;
}

int main() {
	SListNode* PList = NULL;
	SListPushBack(&PList, 1);
	SListPrint(PList);
	SListPushBack(&PList, 2);
	SListPrint(PList);
	SListPushBack(&PList, 3);
	SListPrint(PList);
	SListPushBack(&PList, 4);
	SListPrint(PList);
	SListPushBack(&PList, 5);
	SListPrint(PList);
	SListPushBack(&PList, 7);
	SListPrint(PList);
	SListPushFront(&PList, 6);
	SListPrint(PList);
	SListPopBack(&PList);
	SListPrint(PList);
	SListPopFront(&PList);   
	SListPrint(PList);
	SListInsertAfter(SListFind(PList, 5), 6);
	SListPrint(PList);
	SListEraseAfter(SListFind(PList, 4));
	SListPrint(PList);

}
